package org.sport.logic;

import org.sport.dbImplement.UserOpeImp;
import org.sport.init.SportServerSymbol;
import org.sport.model.entityModel.UsertableEntity;
import org.sport.model.jsonModel.JsonUser;
import org.sport.model.jsonModel.JsonUserImg;
import org.sport.model.jsonModel.Json_0_set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Date;

/**
 * Created by Allen on 2017/9/11.
 *
 * 控制前端传回来的数据逻辑控制，可以调用操作数据库的DBInterface。
 * 比如一个User登录，前端传来一个JsonUser，该层进行数据解读，调用对应DBInterface进行数据查询，获取数据之后将数据进行对比，可能出现密码错误、该用户名不存在等错误
 */
@Service
public class LogicController {

//    UserOperation userOperation = new UserOperationImp();
    @Autowired
    UserOpeImp userOperation;


    //登陆
    public JsonUser SignIn(JsonUser jsonUser)
    {
        System.out.println("进入SignIn");
        if((jsonUser.getResult() == null) || jsonUser.getResult().equals("") || jsonUser.getResult().equals(" "))
        {

            UsertableEntity usertosearch = new UsertableEntity();
            usertosearch.setPhoneNumber(jsonUser.getPhoneNumber());

            UsertableEntity usertosearch2 = userOperation.findUserByPhone(usertosearch);
            //要进行判空，看user是否找到
            if(usertosearch2== null)
            {
                System.out.println("没找到对应user");
                jsonUser.setResult("用户不存在");
            }
            else
            {
                System.out.println("找到对应user");
                System.out.println("密码："+usertosearch2.getPassword());
                if(usertosearch2.getPassword().equals(jsonUser.getPassword()))
                {
                    jsonUser.setResult("登录成功");
                    System.out.println("成功");
                }
                else
                {
                    System.out.println("错误");
                    jsonUser.setResult("密码错误");
                }
            }
        }
        else
        {
            System.out.println("结果已经被填写");
        }
        return jsonUser;
    }


    //注册
    public JsonUser SignUp(JsonUser jsonUser)
    {

        boolean signupStatus = false;
        int     signupcase  =  0;           //注册的各种状态
        System.out.println("进入SignUp");
        if((jsonUser.getResult() == null) || jsonUser.getResult().equals("") || jsonUser.getResult().equals(" ")) {

            UsertableEntity usertosearch = new UsertableEntity();
            usertosearch.setPhoneNumber(jsonUser.getPhoneNumber());
            usertosearch.setPassword(jsonUser.getPassword());
            //先查找是否有一样的用户名
            UsertableEntity usertosearch2 = userOperation.findUserByPhone(usertosearch);
            //为空表示没有相同用户名
            if(usertosearch2 == null) {
                //没有相同用户名用户就开始注册，
                signupStatus = userOperation.addUserEntity(usertosearch);
                if (signupStatus == false)
                    signupcase = 2;
                else
                    signupcase = 3;}
            else
            {signupcase = 1;}


            switch (signupcase)
            {
                case 1:
                    jsonUser.setResult("用户名重复");
                    break;
                case 2:
                    System.out.println("数据库添加错误");
                    jsonUser.setResult("未知错误");
                    break;
                case 3:
                    jsonUser.setResult("注册成功");
                    break;
                default:
                        break;
            }

        }
        else {
            jsonUser.setResult("result已填写");
        }
        return jsonUser;
    }




    /**
     *  复制整个文件夹内容
     *  @param  oldPath  String  原文件路径  如：c:/fqf
     *  @param  newPath  String  复制后路径  如：f:/fqf/ff
     *  @return  boolean
     */
    private   void  copyFolder(String  oldPath,  String  newPath)  {
        try  {
            (new  File(newPath)).mkdirs();  //如果文件夹不存在  则建立新文件夹
            File  a=new  File(oldPath);
            String[]  file=a.list();
            File  temp=null;
            for  (int  i  =  0;  i  <  file.length;  i++)  {
                if(oldPath.endsWith(File.separator)){
                    temp=new  File(oldPath+file[i]);
                }
                else{
                    temp=new  File(oldPath+File.separator+file[i]);
                }

                if(temp.isFile()){
                    FileInputStream input  =  new  FileInputStream(temp);
                    FileOutputStream output  =  new  FileOutputStream(newPath  +  "/"  +
                            (temp.getName()).toString());
                    byte[]  b  =  new  byte[1024  *  5];
                    int  len;
                    while  (  (len  =  input.read(b))  !=  -1)  {
                        output.write(b,  0,  len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if(temp.isDirectory()){//如果是子文件夹
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
        }
        catch  (Exception  e)  {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();
        }
    }


    private SportServerSymbol sportServerSymbol;
    //头像上传
    public JsonUserImg  upLoadImg(JsonUserImg jsonUserImg, MultipartFile file, HttpServletRequest request)
    {

        //需要copy到的path
        String path2 = request.getSession().getServletContext().getRealPath("/0/upload_img");

        //图片本来的存储，暂时可以写死

        String path = sportServerSymbol.ImgStoragePath;;

        String fileName = file.getOriginalFilename();
        System.out.println(path);
        String prefix = "";
        String stuffix = "";

        if(fileName.indexOf(".") >= 0)
        {
            int indexdot = fileName.indexOf(".");
            stuffix = fileName.substring(indexdot);

            prefix = fileName.substring(0,fileName.indexOf("."));
            Date now = new Date();
            prefix = prefix+"_"+now.getTime();
            fileName = prefix + stuffix;
        }


        System.out.println(fileName);

        File targetFile = new File(path,fileName);
        if(!targetFile.exists())
        {
            targetFile.mkdirs();
        }

        //保存
        try{
            file.transferTo(targetFile);
            copyFolder(path,path2);                                 //copy到服务器的文件夹下面
        }catch (Exception e)
        {
            e.printStackTrace();
        }


        UsertableEntity usericon = new UsertableEntity();
        usericon.setPhoneNumber(jsonUserImg.getPhoneNumber());
        usericon = userOperation.findUserByPhone(usericon);
        usericon.setHeadIcon("/0/upload_img/"+fileName);
        userOperation.updateUserEntity(usericon);

        usericon = userOperation.findUserByPhone(usericon);

        jsonUserImg.setIcon(usericon.getHeadIcon());
        jsonUserImg.setNickname(usericon.getName());
        jsonUserImg.setSet_result("设置成功");

        return jsonUserImg;
    }


    //单个头像请求
    public Json_0_set  requestUserImg(Json_0_set jsonUser)
    {
        UsertableEntity usericon = new UsertableEntity();
        usericon.setPhoneNumber(jsonUser.getPhoneNumber());
        usericon = userOperation.findUserByPhone(usericon);

        Json_0_set jsonUserImg = new Json_0_set();
        jsonUserImg.setPhoneNumber(usericon.getPhoneNumber());
        jsonUserImg.setNickname(usericon.getName());
        jsonUserImg.setIconURL(usericon.getHeadIcon());
        jsonUserImg.setResult("设置成功");

        return jsonUserImg;

    }

    //头像list请求

}

